#include <stdio.h>
#include <fcntl.h>      //fcntl()
#include <stdlib.h>     //exit()
#include <sys/socket.h> //socket()
#include <sys/types.h>  //
#include <netinet/in.h> //struct sockaddr_in
#include <errno.h>      //perror()
#include <string.h>     //memset()
#include <unistd.h>     //close()
#include <arpa/inet.h>  //inet_addr
#include <string>

int main(int argn, char **argv)
{
    int nRet;

    uint16_t listenPort = 12344;
    uint16_t clientPort = 12355;

    printf("start create tcp client socket\n");
    int client = socket(AF_INET, SOCK_STREAM, 0);
    if (client == -1) //if (client == RTPSOCKERR)
    {
        printf("Can't create client socket\n");
        return -1;
    }
    printf("create tcp client socket [%d]\n", client);

    struct sockaddr_in clientAddr;
    memset(&clientAddr, 0, sizeof(clientAddr));
    // clientAddr.sin_addr.s_addr = INADDR_LOOPBACK; //inet_addr("127.0.0.1");
    // clientAddr.sin_addr.s_addr = INADDR_ANY; //inet_addr("0.0.0.0");
    clientAddr.sin_family = AF_INET;
    clientAddr.sin_port = htons(clientPort);

    printf("client socket [%d] start bind [%d]\n", client, clientPort);
    nRet = bind(client, (sockaddr *)&clientAddr, sizeof(clientAddr));
    if (nRet != 0)
    {
        close(client);
        printf("client socket [%d] Can't bind client socket\n", client);
        return -1;
    }
    printf("client socket [%d] bind port %d\n", client, clientPort);

    struct sockaddr_in serverAddr;
    serverAddr.sin_addr.s_addr = INADDR_LOOPBACK; //inet_addr("127.0.0.1");
    // serverAddr.sin_addr.s_addr = INADDR_ANY; //inet_addr("0.0.0.0");
    serverAddr.sin_family = AF_INET;
    clientAddr.sin_port = htons(listenPort);
    printf("client socket [%d] start connect %d\n", client, listenPort);
    // int connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen);
    nRet = connect(client, (sockaddr *)&clientAddr, sizeof(clientAddr));
    if (nRet < 0)
    {
        printf("client socket [%d] connect error\n", client);
        close(client);
        return -1;
    }

    printf("input [SOCKET: %d, IP：%s,  PORT：%d]\n", client, inet_ntoa(serverAddr.sin_addr), ntohs(serverAddr.sin_port));

    size_t length = 1024 * 16;
    char buffer[1024 * 16];
    ssize_t recvLength;
    //ssize_t recv(int socket, void *buffer, size_t length, int flags);
    while (1)
    {
        recvLength = recv(client, buffer, length, 0);
        if (recvLength < 0)
        {
            perror("sockert recv error:");
            close(client);
            break;
        }

        std::string data = std::string(buffer, recvLength);
        printf("recv:%s\n", data.c_str());
    }

    printf("Hello World!\n");
    return 0;
}